package com.xiaotu.code.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;

/**
 * 针对时间的处理工具类.
 * 
 * @author chenxiangrong
 * 
 */
public class DateUtil {
	/**
	 * 获取当前格式化的时间(字符串).
	 * 
	 * @param pattern
	 * @return
	 */
	public static String getCurrentFormatDateStr(String pattern) {
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		dateFormat.format(now);
		return dateFormat.format(now);
	}

	/**
	 * 两个日期比较（ 截止如期小于当前日期，过期，返回true；否则，未过期，返回false）.
	 * 
	 * @param currentDate
	 * @param deadLine
	 * @param pattern
	 * @return
	 * @throws ParseException
	 */
	public static boolean isOverTime(Date currentDate, Date deadLine,
			String pattern) throws ParseException {
		String dt = new String(new SimpleDateFormat(pattern)
				.format(currentDate));
		DateFormat f = new java.text.SimpleDateFormat(pattern);
		Date nowDate = f.parse(dt);
		return deadLine.before(nowDate);
	}

	/**
	 * 多少时间以后.
	 * 
	 * @param type
	 *            (1:年;2:月;3:周;4:天;5:小时;6:分)
	 * @param length(时长)
	 * @param currentDate(当前时间)
	 * @param pattern(时间格式)
	 * @return
	 * @throws ParseException
	 */
	public static Date afterNDate(int type, int length, Date currentDate,
			String pattern) throws ParseException {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
		String nowDateStr = simpleDateFormat.format(currentDate);
		switch (type) {
		case 1:
			currentDate=DateUtils.addYears(currentDate, length);
			break;
		case 2:
			currentDate=DateUtils.addMonths(currentDate, length);
			break;
		case 3:
			currentDate=DateUtils.addWeeks(currentDate, length);
			break;
		case 4:
			currentDate=DateUtils.addDays(currentDate, length);
			break;
		case 5:
			currentDate=DateUtils.addHours(currentDate, length);
			break;
		case 6:
			currentDate = DateUtils.addMinutes(currentDate, length);
			break;
		default:
			currentDate = DateUtils.addDays(simpleDateFormat.parse(nowDateStr),
					length);
			break;
		}
		return currentDate;
	}
}
